package com.uaf.aes.utils;

import java.io.*;

/**
 * @author cailu
 * @filename FileStreamUtils
 * @description
 * @date 2020/5/6 13:41
 */
public class FileStreamUtils {

	/**
	 * 功能描述  保存为本地文件
	 * @param path    本地文件路径
	 * @param content 内容
	 * @return void
	 * @author cailu
	 * @date 2020/5/6 13:41
	 */
	public static void writeToString(String path, String content) {
		FileOutputStream fop = null;
		File file;
		try {
			String dirs = path.substring(path.lastIndexOf("\\"));
			String dir = path.substring(0, path.length() - dirs.length());
			file = new File(dir);
			if (!file.exists()) {
				file.mkdirs();
			}
			file = new File(path);
			fop = new FileOutputStream(file);
			if (!file.exists()) {
				file.createNewFile();
			}
			byte[] contentInBytes = content.getBytes();
			fop.write(contentInBytes);
			fop.flush();
			fop.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fop != null) {
					fop.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 功能描述  获取本地文件
	 * @param path 本地文件路径
	 * @return java.lang.String
	 * @author cailu
	 * @date 2020/5/6 13:42
	 */
	public static String readToString(String path) {
		String encoding = "UTF-8";
		File file = new File(path);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}
}
